﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Logger;
using Common.BaseLibrary.Utils;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;

namespace DepartmentWork.Platform.Areas.ProjectManageArea.Controllers
{
    public class WorkReocredController : BaseController
    {
        //
        // GET: /ProjectManageArea/WorkReocred/

        public ActionResult Index(string projectId, string flag = "", string info = "")
        {
            #region 校验身份

            #region 原版

            //string[] pathArr = Request.Path.Split('/');
            //Guid userGuid = new Guid(CurrentUser.UserID);
            //USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            //USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            //ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            //List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
            //for (int i = 0; i < menuRole.Count(); i++)
            //{
            //    int menuId = menuRole[i].MENU_ID;
            //    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
            //    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
            //    {
            //        ViewBag.IsAdmin = true;
            //        break;
            //    }
            //}

            #endregion

            #region 改版后

            //1 、 获取当前用户所在角色
            //2. 获取该角色 所具有的 所有 权限
            //3. 确认该角色是否具有该权限
            Guid userGuid = new Guid(CurrentUser.UserID);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            List<AUTHORITY_ROLE> authRoleList =
                authorityRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();



            for (int i = 0; i < authRoleList.Count; i++)
            {
                bool result = false;
                result =
                    empAuthorityRepository.GetModel(r => r.AUTHORITY_ID == authRoleList[i].AUTHORITY_ID)
                        .FirstOrDefault()
                        .AUTHORITY_TITLE.Contains("项目管理工作记录操作");
                if (result == true)
                {
                    ViewBag.IsAdmin = true;
                    break;

                }
            }

            #endregion

            #endregion

            #region 设置分页

            var pageSizeExecute = this.Request["pageSizeExecute"] == null ? 10 : int.Parse(Request["pageSizeExecute"]);
            var pageIndexExecute = this.Request["pageIndexExecute"] == null ? 1 : int.Parse(Request["pageIndexExecute"]);

            ViewData["pageIndexExecute"] = pageIndexExecute;
            ViewData["pageSizeExecute"] = pageSizeExecute;

            var pageSize = this.Request["pageSizeFinish"] == null ? 10 : int.Parse(Request["pageSizeFinish"]);
            var pageIndex = this.Request["pageIndexFinish"] == null ? 1 : int.Parse(Request["pageIndexFinish"]);

            ViewData["pageIndexFinish"] = pageIndex;
            ViewData["pageSizeFinish"] = pageSize;

            var pageSizeAll = this.Request["pageSizeAll"] == null ? 10 : int.Parse(Request["pageSizeAll"]);
            var pageIndexAll = this.Request["pageIndexAll"] == null ? 1 : int.Parse(Request["pageIndexAll"]);

            ViewData["pageIndexAll"] = pageIndexAll;
            ViewData["pageSizeAll"] = pageSizeAll;


            #endregion

            
            

            ProjectWorkReocredViewModel model = new ProjectWorkReocredViewModel();
            Guid proId = new Guid(projectId);
            ViewBag.ProjectName =
                projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId)
                    .FirstOrDefault()
                    .PROJECT_MANAGEMENT_TITLE;
            ViewBag.ProjectId = projectId;
            IList<PROJECT_WORKRECORD> projectWorkRecordAllList = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId).OrderByDescending(r => r.PROJECT_WORKRECORD_CREATETIME).Take(pageSizeAll * pageIndexAll).Skip(pageSizeAll * (pageIndexAll - 1)).ToList();

            IList<PROJECT_WORKRECORD> projectWorkRecordNormalList = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId && r.LEVEL == 0).OrderByDescending(r => r.PROJECT_WORKRECORD_CREATETIME).Take(pageSizeExecute * pageIndex).Skip(pageSizeExecute * (pageIndexExecute - 1)).ToList();

            IList<PROJECT_WORKRECORD> projectWorkRecordImportantList = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId && r.LEVEL == 1).OrderByDescending(r => r.PROJECT_WORKRECORD_CREATETIME).Take(pageSize * pageIndex).Skip(pageSize * (pageIndex - 1)).ToList();
            model.NormalProjectWorkReocredList = new DataSet();
            model.ImportantProjectWorkReocredList = new DataSet();
            model.NormalProjectWorkAllList=new DataSet();
            model.NormalProjectWorkReocredList = DataSetHelp.Instance.ToDataSet(projectWorkRecordNormalList);
            model.ImportantProjectWorkReocredList = DataSetHelp.Instance.ToDataSet(projectWorkRecordImportantList);
            model.NormalProjectWorkAllList = DataSetHelp.Instance.ToDataSet(projectWorkRecordAllList);
            model.NormalProjectWorkReocredList.Tables[0].Columns.Add("CREATER_NAME");
            model.ImportantProjectWorkReocredList.Tables[0].Columns.Add("CREATER_NAME");
            model.NormalProjectWorkAllList.Tables[0].Columns.Add("CREATER_NAME");

            for (int i = 0; i < model.NormalProjectWorkAllList.Tables[0].Rows.Count; i++)
            {
                DataRow dr = model.NormalProjectWorkAllList.Tables[0].Rows[i];
                Guid userId = new Guid(dr["PROJECT_WORKRECORD_CREATER"].ToString());
                dr["CREATER_NAME"] = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;
            }

            for (int i = 0; i < model.NormalProjectWorkReocredList.Tables[0].Rows.Count; i++)
            {
                DataRow dr = model.NormalProjectWorkReocredList.Tables[0].Rows[i];
                Guid userId = new Guid(dr["PROJECT_WORKRECORD_CREATER"].ToString());
                dr["CREATER_NAME"] = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;
            }

            for (int i = 0; i < model.NormalProjectWorkReocredList.Tables[0].Rows.Count; i++)
            {
                DataRow dr = model.NormalProjectWorkReocredList.Tables[0].Rows[i];
                Guid userId = new Guid(dr["PROJECT_WORKRECORD_CREATER"].ToString());
                dr["CREATER_NAME"] = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;
            }

            ViewData["totalAll"] = projectWorkRecordAllList.Count();
            ViewData["totalExecute"] = projectWorkRecordNormalList.Count();
            ViewData["totalFinish"] = projectWorkRecordImportantList.Count();
            return View(model);
        }

        /// <summary>
        /// 零散工作记录
        /// </summary>
        /// <returns></returns>
        public ActionResult OtherWorkReocred(string flag="")
        {
            var pageSize = this.Request["pageSize"] == null ? 10 : int.Parse(Request["pageSize"]);
            var pageIndex = this.Request["pageIndex"] == null ? 1 : int.Parse(Request["pageIndex"]);

            ViewData["pageIndex"] = pageIndex;
            ViewData["pageSize"] = pageSize;

            ProjectWorkReocredViewModel model=new ProjectWorkReocredViewModel();

            model.NormalProjectWorkAllList=new DataSet();

            IList<PROJECT_WORKRECORD> projectWorkRecordNormalList =
                projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == null).OrderByDescending(r => r.PROJECT_WORKRECORD_CREATETIME).Take(pageSize * pageIndex).Skip(pageSize * (pageIndex - 1)).ToList();

            ViewData["total"] = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == null).Count();
            
           model.NormalProjectWorkAllList = DataSetHelp.Instance.ToDataSet(projectWorkRecordNormalList);
            model.NormalProjectWorkAllList.Tables[0].Columns.Add("CREATER_NAME");
           for (int i = 0; i < model.NormalProjectWorkAllList.Tables[0].Rows.Count; i++)
           {
               DataRow dr = model.NormalProjectWorkAllList.Tables[0].Rows[i];
               Guid userId = new Guid(dr["PROJECT_WORKRECORD_CREATER"].ToString());
               dr["CREATER_NAME"] = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;
           }
           return this.View(model);
        }

        [HttpPost]
        public ActionResult CreateWorkReocred(FormCollection collection)
        {
            try
            {
                PROJECT_WORKRECORD model = new PROJECT_WORKRECORD();
                model.PROJECT_WORKRECORD_TITLE = collection["tb_ProjectWorkReocredTitle"];
                model.PROJECT_WORKRECORD_CONTENT = collection["tb_ProjectWorkReocredDescription"];
                if (collection["select_ProjectWorkReocredLevel"]==null)
                {
                    model.LEVEL = 3;
                }
                else
                {
                    model.LEVEL = Convert.ToInt32(collection["select_ProjectWorkReocredLevel"]);
                }


                if (collection["hid_ProjectId"] == null)
                {
                    model.PROJECT_MANAGEMENT_ID = null;
                }
                else
                {
                    model.PROJECT_MANAGEMENT_ID = new Guid(collection["hid_ProjectId"]);
                }
                
                model.PROJECT_WORKRECORD_CREATER = new Guid(CurrentUser.UserID);
                model.PROJECT_WORKRECORD_CREATETIME =DateTime.Now;
                model.PROJECT_WORKRECORD_ID = Guid.NewGuid();
                projectWorkReocredRepository.Insert(model);
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "项目工作记录新增成功！");

                if (collection["hid_ProjectId"] != null)
                {
                    return RedirectToAction("Index", "WorkReocred", new { area = "ProjectManageArea", flag = "CreateTrue", projectId = collection["hid_ProjectId"] });
                }
                else
                {
                    return RedirectToAction("OtherWorkReocred", "WorkReocred", new { area = "ProjectManageArea", flag = "CreateTrue" });
                }

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "项目工作记录新增失败！信息：" + ex.Message);

                return RedirectToAction("Index", "WorkReocred", new { area = "ProjectManageArea", flag = "CreateFalse", info = ex.Message, projectId = collection["hid_ProjectId"] });
            }
        }

        [HttpPost]
        public ActionResult EditWorkReocred(FormCollection collection)
        {
            try
            {
                Guid workReocredId = new Guid(collection["hid_EditProjectWorkReocred"]);
                PROJECT_WORKRECORD model = projectWorkReocredRepository.GetModel(r => r.PROJECT_WORKRECORD_ID == workReocredId).FirstOrDefault();

                model.PROJECT_WORKRECORD_TITLE = collection["tb_EditProjectWorkReocredTitle"].Trim() == "" ? model.PROJECT_WORKRECORD_TITLE : collection["tb_EditProjectWorkReocredTitle"];
                model.PROJECT_WORKRECORD_CONTENT = collection["tb_EditProjectWorkReocredDescription"].Trim() == "" ? model.PROJECT_WORKRECORD_TITLE : collection["tb_EditProjectWorkReocredDescription"];
                model.PROJECT_WORKRECORD_CREATER = new Guid(CurrentUser.UserID);
                model.PROJECT_WORKRECORD_CREATETIME = DateTime.Now;
                model.LEVEL = Convert.ToInt32(collection["select_EditProjectWorkReocredLevel"]);
                projectWorkReocredRepository.Update(model);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "项目工作记录编辑成功！");

                return RedirectToAction("Index", "WorkReocred", new { area = "ProjectManageArea", flag = "EditTrue", projectId = collection["hid_ProjectId"] });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "项目工作记录编辑失败！信息：" + ex.Message);

                return RedirectToAction("Index", "WorkReocred", new { area = "ProjectManageArea", flag = "EditFalse", info = ex.Message, projectId = collection["hid_ProjectId"] });
            }

        }

        [HttpPost]
        public JsonResult GetWorkReocredInfo(Guid workReocredId)
        {
            PROJECT_WORKRECORD pro = projectWorkReocredRepository.GetModel(r => r.PROJECT_WORKRECORD_ID == workReocredId).FirstOrDefault();

            ProjectWorkReocredInfoViewModel model = new ProjectWorkReocredInfoViewModel();

            model.PROJECT_MANAGEMENT_ID = pro.PROJECT_MANAGEMENT_ID;
            model.PROJECT_WORKRECORD_CONTENT = pro.PROJECT_WORKRECORD_CONTENT;
            model.PROJECT_WORKRECORD_CREATER = pro.PROJECT_WORKRECORD_CREATER;
            Guid userId = model.PROJECT_WORKRECORD_CREATER;
            model.PROJECT_WORKRECORD_CREATERNAME =
                userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;

            model.PROJECT_WORKRECORD_CREATETIME = pro.PROJECT_WORKRECORD_CREATETIME;
            model.PROJECT_WORKRECORD_ID = pro.PROJECT_WORKRECORD_ID;
            model.PROJECT_WORKRECORD_TITLE = pro.PROJECT_WORKRECORD_TITLE;
            model.LEVEL = pro.LEVEL;
            return this.Json(model);
        }

        public ActionResult DelWorkReocred(Guid workReocredId)
        {
            PROJECT_WORKRECORD model = projectWorkReocredRepository.GetModel(r => r.PROJECT_WORKRECORD_ID == workReocredId).FirstOrDefault();
            string proId = model.PROJECT_MANAGEMENT_ID.ToString();
            try
            {
                projectWorkReocredRepository.Delete(model);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "项目工作记录删除成功！");

                return RedirectToAction("Index", "WorkReocred", new { area = "ProjectManageArea", flag = "DelTrue", projectId = proId });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "项目工作记录删除失败！信息：" + ex.Message);

                return RedirectToAction("Index", "WorkReocred", new { area = "ProjectManageArea", flag = "DelFalse", info = ex.Message, projectId = proId });
            }

        }
    }
}
